package servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


import pojo.Categories;
import pojo.MerchantClient;
import pojo.MerchantDto;
import pojo.PageBean;
import service.CategoriesManager;
import service.MerchantManager;
import service.factory.ManagerFactory;
import util.HttpUtil;
import util.JsonUtil;

public class ShowMerchantsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private final static Logger logger = LogManager.getLogger(ShowMerchantsServlet.class);
	private MerchantManager manager;
	private CategoriesManager categoriesManager;
       
    public ShowMerchantsServlet() {
        super();
       manager = ManagerFactory.getMerchantManagerInstance();
       categoriesManager = ManagerFactory.getCategoriesManagerInstance();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String currold = request.getParameter("curr");
		String typeId = (String)request.getAttribute("typeId");
		
		if(currold == null){
			currold = "1";
		}
		int curr = Integer.parseInt(currold);
		List<MerchantClient> list = null;
		List<Categories> categoriesList = categoriesManager.findAll();
		categoriesList.add(0,new Categories("all","all"));
		String typeName = null;
		if(typeId == null || "all".equals(typeId)){
			typeId = "all";
			typeName ="all";
		}
		else{
			typeName=categoriesManager.load(typeId).getType();
		}
		List<MerchantDto> correctMerchants = null;
		try {
			String merchantString = HttpUtil.getResponseStr("http://ZHA-ITA077-w7:8080/admins/c/all");
			correctMerchants = (List<MerchantDto>) JsonUtil.toJsonListObject(merchantString, List.class, MerchantDto.class);
//			correctMerchants = Test.getList();
		} catch (Exception e) {
			logger.info("can not connect server....");
			String info = "can not connect server....";
			request.getRequestDispatcher("/error?info=" + info).forward(request, response);
			return;
		}
		
		int pageSize = (int)this.getServletContext().getAttribute("pageSize");
		list = manager.findByTypePage(curr,pageSize,typeId, correctMerchants);
		int count = manager.getCount(typeId, correctMerchants);
		PageBean<MerchantClient> pageBean = new PageBean<MerchantClient>(curr, pageSize, list, count);
		
		request.setAttribute("typeName", typeName);
		request.setAttribute("typeId", typeId);
		request.setAttribute("categoriesList", categoriesList);
		request.setAttribute("pageBean", pageBean);
		request.getRequestDispatcher("showMerchants.jsp").forward(request, response);
	}
}
